package com.yehuo.app.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yehuo.app.entity.Page;
import com.yehuo.app.entity.SensitiveMessage;
import com.yehuo.app.entity.User;
import com.yehuo.app.mapper.SensitiveMessageMapper;
import com.yehuo.app.mapper.UserMapper;
import com.yehuo.app.model.R;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 敏感词消息管理
 */
@RestController
@RequestMapping("/sensitive/message")
public class SensitiveMessageController {

    @Resource
    private SensitiveMessageMapper sensitiveMessageMapper;

    @Resource
    private UserMapper userMapper;

    /**
     * @param page
     * @return
     */
    @RequestMapping("/list")
    public R list(Page page) {
        //开启分页
        PageHelper.startPage(page.getPage(), page.getLimit());
        List<SensitiveMessage> list = sensitiveMessageMapper.selectList(null);
        list.forEach(o -> {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("_uid", o.getTarget());
            User user = userMapper.selectOne(queryWrapper);
            if (user != null) {
                o.setRecipient(user.getNickname());
            }
        });
        PageInfo<SensitiveMessage> pageInfo = new PageInfo<>(list);
        R<SensitiveMessage> result = new R<SensitiveMessage>((int) pageInfo.getTotal(), pageInfo.getList());
        return result;
    }


    /**
     * 删除
     *
     * @param id
     * @return
     */
    @RequestMapping("/remove/{id}")
    public R remove(@PathVariable("id") Integer id) {
        int i = sensitiveMessageMapper.deleteById(id);
        R<Integer> result = new R<>();
        result.setCode(0);
        result.setMsg(i > 0 ? "删除成功" : "删除失败");
        return result;
    }

    /**
     * 清空
     *
     * @return
     */
    @RequestMapping("/clean")
    public R clean() {
        List<SensitiveMessage> list = sensitiveMessageMapper.selectList(null);
        AtomicInteger count = new AtomicInteger();
        list.forEach(o -> {
            count.addAndGet(sensitiveMessageMapper.deleteById(o.getId()));
        });
        R<Integer> result = new R<>();
        result.setCode(0);
        result.setMsg(count.get() >= 0 ? "清空成功" : "清空失败");
        return result;
    }
}
